﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TSUnion.KMIP.Configuration
{
    public class KmipConfigurationManager
    {

        public static Object ConfigureObject(Object obj) 
        {
            var type = obj.GetType();
            List<PropertyInfo> properties = type.GetProperties(BindingFlags.Instance|BindingFlags.NonPublic | BindingFlags.Public).ToList();
            foreach (var property in properties)
            {
                if(Attribute.IsDefined(property, typeof(AppSettingAttribute)))
                {
                    var appSettingName=type.FullName + "." + property.Name;
                    if (System.Configuration.ConfigurationManager.AppSettings[appSettingName] != null)
                    {

                        var propertyValue = System.Configuration.ConfigurationManager.AppSettings[appSettingName];
                        var propertyType = property.PropertyType;
                        if (property.PropertyType.IsEnum) 
                        {
                            property.SetValue(obj, Enum.Parse(propertyType, propertyValue),null);
                        }
                        else
                        {
                            property.SetValue(obj, Convert.ChangeType(propertyValue, propertyType), null);
                        }
                    }
                }
            }

            return obj;
        
        }
    }
}
